<template>
  <view class="content">
    <u-checkbox-group placement="column" @change="checkboxChange">
      <view class="goods">
        <view class="goods_item" v-for="(item, index) in cartGoodsInfo" :key="index">
          <u-checkbox :name="index" shape="circle" activeColor="#ff0000" :checked="item.checked"> </u-checkbox>
          <view class="product-image">
            <image :src="item.goodsImage" @click="goDetail(item)"></image>
          </view>
          <view class="goods_option">
            <view style="height: 100%">
              <view class="goods_name">{{ item.goodsName }}</view>
              <view style="display: flex">
                <view class="sku_name" @click="openSku(item, index)">
                  {{ item.skuName }}
                  <u-icon name="arrow-down" color="#ccc" size="10"></u-icon>
                </view>
              </view>
            </view>
            <view class="price_option">
              <view class="price">￥{{ item.skuPresentPrice }}</view>
              <u-number-box v-model="value">
                <template #minus>
                  <view class="minus" @click="numChange(0, item)"> - </view>
                </template>
                <template #input>
                  <input class="minus_input" @input="numInputChange($event, item)" v-model="item.num" />
                </template>
                <template #plus>
                  <view class="minus" @click="numChange(1, item)"> + </view>
                </template>
              </u-number-box>
            </view>
          </view>
        </view>
      </view>
    </u-checkbox-group>

    <view class="bottom">
      <view style="display: flex; align-items: center; height: 100%">
        <u-checkbox-group placement="row" @change="checkboxAllChange">
          <u-checkbox shape="circle" activeColor="#ff0000" label="全选" :checked="checkedAll"></u-checkbox>
        </u-checkbox-group>
        <view class="price" style="font-size: 26rpx; margin-left: 10rpx"> 合计：￥{{ totalData.price }} </view>
      </view>
      <view style="display: flex">
        <button :class="['btns', cartGoodsRealBuy.length > 0 ? 'enabled' : 'disabled']" @click="del">删除</button>
        <view class="btns realbuy" @click="goBuy">去结算（{{ totalData.num }}）</view>
      </view>
    </view>

    <view style="height: 500rpx"></view>
    <skuDailog :hadTar="true" :skuVisble="skuVisble" :detailInfo="detailInfo" @inCartById="inCartById" @handleClose="skuClose"></skuDailog>
  </view>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { getGoodsInfo } from "@/utils/api";
import skuDailog from "../../pages/goodsDetail/skuDailog.vue";

const skuVisble = ref(false);

const detailInfo = ref({});
const clickIndexSku = ref(0);
async function openSku(item, index) {
  clickIndexSku.value = index;
  let { code, data } = await getGoodsInfo({ goodsId: item.goodsId });
  if (code == 200) {
    detailInfo.value = data.detail;
    skuVisble.value = true;
  }
}

function skuClose() {
  skuVisble.value = false;
}

const props = defineProps({
  tabIndex: {
    type: Number,
    default: () => 0,
  },
  selfIndex: {
    type: Number,
    default: () => 0,
  },
});

watch(
  () => props.tabIndex,
  (val) => {
    if (props.selfIndex == val) {
      //onShow
      initCart();
    }
  }
);

onBeforeMount(() => {
  initCart();
});

function initCart() {
  cartGoodsInfo.value = uni.getStorageSync("cartGoodsInfo");

  if (cartGoodsInfo.value) {
    let arr = [];
    const result = cartGoodsInfo.value.reduce((acc, cur) => {
      if (acc[cur.skuId]) {
        acc[cur.skuId] += cur.num;
      } else {
        acc[cur.skuId] = cur.num;
        arr.push(cur);
      }
      return acc;
    }, {});
    cartGoodsInfo.value = JSON.parse(JSON.stringify(arr));
  }
}

const checkedAll = ref();
const totalData = reactive({
  price: 0,
  num: 0,
});
const cartGoodsInfo = ref([]);
const cartGoodsRealBuy = ref([]);

//全选
function checkboxAllChange(val) {
  let arr = [];

  if (val.length > 0) {
    cartGoodsInfo.value.forEach((item, index) => {
      item.checked = true;
      arr.push(index);
    });
  } else {
    let arr = [];
    cartGoodsInfo.value.forEach((item, index) => {
      item.checked = false;
    });
  }
  checkboxChange(arr);
}

//单个checkbox选中
function checkboxChange(val) {
  //如果全部都被取消了，取消全选
  if (val.length <= 0) {
    checkedAll.value = false;
  } else if (val.length == cartGoodsInfo.value.length) {
    checkedAll.value = true;
  }
  //选中状态放入集合中
  cartGoodsInfo.value.forEach((item, index) => {
    if (val.includes(index)) {
      item.checked = true;
    } else {
      item.checked = false;
    }
  });

  //计算总价和数量
  totalData.price = 0;
  totalData.num = 0;
  let arr = [];
  val.forEach((item) => {
    if (cartGoodsInfo.value[item]) {
      arr.push(cartGoodsInfo.value[item]);
      totalData.price = Number(totalData.price) + Number(cartGoodsInfo.value[item].skuPresentPrice) * cartGoodsInfo.value[item].num;
      totalData.price = totalData.price.toFixed(2);
      totalData.num++;
    }
  });

  cartGoodsRealBuy.value = arr;
}

function numInputChange(event, item) {
  item.num = event.detail.value;

  let arr = [];
  cartGoodsInfo.value.forEach((item, index) => {
    if (item.checked) {
      arr.push(index);
    }
  });
  checkboxChange(arr);
  uni.setStorageSync("cartGoodsInfo", cartGoodsInfo.value);
}

//数量变化
function numChange(type, item) {
  if (type == 0) {
    if (item.num > 0) item.num--;
  } else {
    item.num++;
  }

  uni.setStorageSync("cartGoodsInfo", cartGoodsInfo.value);

  let arr = [];
  cartGoodsInfo.value.forEach((item, index) => {
    if (item.checked) {
      arr.push(index);
    }
  });
  checkboxChange(arr);
}

function del() {
  let copy = [];
  cartGoodsInfo.value.forEach((item, index) => {
    if (!item.checked) {
      copy.push(item);
    }
  });
  cartGoodsInfo.value = copy;
  // checkboxAllChange([]);
  checkboxChange([]);
  uni.setStorageSync("cartGoodsInfo", cartGoodsInfo.value);
}

function goBuy() {
  if (cartGoodsRealBuy.value.length <= 0) {
    uni.showToast({
      title: "请选择一个商品去结算",
    });
    return;
  }
  uni.navigateTo({
    url: "/pages/goodsDetail/orderConfirm?info=" + JSON.stringify(cartGoodsRealBuy.value),
  });
}

function goDetail(item) {
  uni.navigateTo({
    url: "/pages/goodsDetail/index?id=" + item.goodsId,
  });
}

function inCartById(reItem) {
  cartGoodsInfo.value[clickIndexSku.value] = reItem;
  skuVisble.value = false;
  uni.setStorageSync("cartGoodsInfo", cartGoodsInfo.value);
}
</script>

<style lang="scss" scoped>
.content {
  background-color: #f6f6f6;
  position: relative;
}

.goods {
  margin: 30rpx;
  background-color: white;
  border-radius: 20rpx;
  padding: 20rpx;
}

.goods_item {
  display: flex;
  height: 180rpx;
  border-bottom: 1px solid #f6f6f6;
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  align-items: center;
}

.product-image image {
  width: 170rpx;
  height: 170rpx;
  // background-color: red;
  margin-right: 30rpx;
}

.goods_option {
  width: 60%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.goods_name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 30rpx;
}

.sku_name {
  font-size: 24rpx;
  color: #ccc;
  margin-top: 20rpx;
  display: flex;
  background-color: #f6f6f6;
  text-align: center;
  justify-content: center;
  align-items: center;
  padding: 5rpx 15rpx;
  border-radius: 100rpx;
}

.price {
  font-size: 36rpx;
  color: #d23000;
  font-weight: 600;
}

.price_option {
  display: flex;
  justify-content: space-between;
}

.minus {
  width: 40rpx;
  height: 40rpx;
  background-color: #f6f6f6;
  display: flex;
  font-size: 20rpx;
  text-align: center;
  justify-content: center;
  align-items: center;
}

.minus_input {
  width: 40rpx;
  height: 30rpx;
  font-size: 20rpx;
  border: 1px solid #f6f6f6;
  display: flex;
  text-align: center;
}

.bottom {
  position: fixed;
  bottom: 170rpx;
  width: 95vw;
  height: 100rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 0 30rpx;
}

.btns {
  width: 150rpx;
  height: 60rpx;
  line-height: 150rpx;
  font-size: 22rpx;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 100rpx;
}

.realbuy {
  background-color: rgb(57, 156, 255);
  margin-left: 30rpx;
}

.enabled {
  background-color: red;
}

.disabled {
  background-color: #ccc;
}
</style>
